const $wx = require('./$wxes.js');

const GLOBAL_CONFIG = new Object();
const SET_GLOBAL_CONFIG = (callback) => {
  $wx.isFun(callback) && callback(GLOBAL_CONFIG);
}

/**
 * @parma 'url'
 * @parma {data}
 * @parma {config}
 * */
function $requset(url, data = {}, config = {}) {
  switch (data.loadType) {
    case 'default':
      wx.showLoading({ title: data.loadMsg });
      delete data.loadMsg;
    case 'bar':
      wx.showNavigationBarLoading();
  }

  return new Promise((resolve, reject) => {
    config.url = url;
    config.data = data;

    // console.log(!$wx.objIsNull(GLOBAL_CONFIG).length > 0);

    if (!$wx.objIsNull(GLOBAL_CONFIG)) {
      if ($wx.isFun(GLOBAL_CONFIG._header)) {
        config.header = GLOBAL_CONFIG._header();
      }

      if ($wx.isFun(GLOBAL_CONFIG._success)) {
        config.success = res => GLOBAL_CONFIG._success(res, resolve);
      }

      if ($wx.isFun(GLOBAL_CONFIG._fail)) {
        config.fail = error => GLOBAL_CONFIG._fail(error, reject);
      }
      // config = Object.assign(GLOBAL_CONFIG, config);

    } else {
      config.success = res => resolve(res);
      config.fail = error => reject(error);
    }

    config.complete = () => {
      switch (data.loadType) {
        case 'default':
          wx.hideLoading();
        case 'bar':
          wx.hideNavigationBarLoading();
      }
    }

    wx.request(config);
  });

}

const GET = (url, data, config = {}) => {
  return $requset(url, data, config);
}

const POST = (url, data, config = {}) => {
  config.method = 'POST';
  return $requset(url, data, config);
}

const DELETE = (url, data, config = {}) => {
  config.method = 'DELETE';
  return $requset(url, data, config);
}

module.exports = {
  SET_GLOBAL_CONFIG,
  GET,
  POST,
  DELETE
};